package concurrents.pool;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Glogo on 2014/9/1.
 * 使用JDK提供的框架Executors去创建线程池
 */
public class MyThreadPoolDemo3 {

    private int port = 8888;
    private String host = "localhost";
    private ServerSocket serverSocket;
    private ExecutorService executorService;    //线程池的向上接口

    private final int POOL_SIZE = 4;

    public MyThreadPoolDemo3() throws IOException {
        serverSocket = new ServerSocket();
        serverSocket.bind(new InetSocketAddress(host, port));
//        System.out.println(Runtime.getRuntime().availableProcessors());
        executorService = Executors.newFixedThreadPool(
          Runtime.getRuntime().availableProcessors()*POOL_SIZE
        );
        System.out.println("服务器启动");
    }

    public void service() {
        while(true){
            Socket socket = null;
            try {
                socket = serverSocket.accept();
                executorService.execute(new Handler(socket));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) throws IOException {
        new MyThreadPoolDemo3().service();
    }

    private class Handler implements Runnable{
        private Socket socket;
        public Handler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            System.out.println(socket.toString());
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
